package org.shoukaiseki.tools.mybatis.generator;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.*;
import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.velocity.runtime.directive.Foreach;
import org.shoukaiseki.commons.utils.FileUtils;
import org.shoukaiseki.commons.utils.SystemUtils;
import org.shoukaiseki.tools.mybatis.generator.actuator.GeneratorActuator;
import org.shoukaiseki.tools.mybatis.generator.config.GeneratorProperties;
import org.shoukaiseki.tools.mybatis.generator.exception.SksException;
import org.shoukaiseki.tools.mybatis.generator.utils.spring.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import javax.annotation.Resource;
import javax.sound.midi.Soundbank;
import javax.sql.DataSource;

/**
 * <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  18-10-23 下午1:23<br>
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
@SpringBootApplication
@ComponentScan(basePackages = "org.shoukaiseki")
@Slf4j(topic = "org.shoukaiseki.tools.generator")
public class SpringBootConsoleApplication implements CommandLineRunner {


    @Value("${sks.logger.printError:false")
    private String printError;

    @Value("${sks.datasource.url}")
    String url;

    @Value("${sks.datasource.username}")
    String username;

    @Value("${sks.datasource.password}")
    String password;

    static Options options;

    static boolean logEnable=false;

    //true:如果文件已存在则强制覆盖
    static boolean force=false;


    static CommandLine cmd;

    static CommandLineParser parser;

    @Bean
    public CommandLine commandLine(){
        return this.cmd;
    }

    public static void main(String[] args)  {
//        String[] args = { "-h" };
//        args = new String[]{ "-help" };
//        args = new String[]{ "-f","gmma.yml" };
        options = new Options();
        options.addOption(new Option("f", "file", true, "要生成代码的配置文件"));
        options.addOption(new Option("l","log", false, "详细日志"));
        options.addOption(new Option("o","force", false, "文件存在时强制覆盖"));
        options.addOption(new Option("h","help", false, "帮助"));
//        System.out.println("---------args="+JSONObject.toJSONString(args));

        parser = new DefaultParser();
        String filename=null;
        try {
            cmd = parser.parse(options, args);
            logEnable=cmd.hasOption("l");
            force=cmd.hasOption("o");
            if (cmd.hasOption("h"))
            {
                printCmdHelp();
                return;
            }else if(cmd.hasOption("f")) {
                filename = cmd.getOptionValue("f");
            }else {
            }
        } catch (ParseException e) {
//            printCmdHelp();
            e.printStackTrace();
        }
        String userPath = System.getProperty("user.dir");
        String pathSeparator = SystemUtils.isLinux()?"/":"\\";
        if(filename==null){
                filename=userPath+pathSeparator+"gmm.yml";
        }else{
            filename=userPath+pathSeparator+filename;
            if(!FileUtils.exists(filename)){
                System.out.println("配置文件["+filename+"] 不存在, -help 可查看帮助");
                System.out.println();
                return;
            }
        }
        if( !FileUtils.exists(filename)){
            filename=userPath+pathSeparator+"gmm.properties";
        }
        if(!FileUtils.exists(filename)){
            System.out.println("默认的 gmm.yml 或者 gmm.properties 配置文件不存在, -help 可查看帮助");
            System.out.println();
            return;
        }
        System.out.println("file="+filename);
        String[] springArgs = {"--spring.config.location=" + filename};
        try{
            SpringApplication.run(SpringBootConsoleApplication.class, springArgs);
        }catch (Throwable t){
        }
    }

    public static void printCmdHelp(){

        // print usage
        HelpFormatter formatter = new HelpFormatter();
        formatter.setSyntaxPrefix("用法:");
        formatter.printHelp( "-f参数为空时默认采用 gmm.yml 配置文件\n" +
                "[options] [target [target2 [target3] ...]] ", options );
    }

//    @Autowired
//    GeneratorActuator generatorActuator;

    @Override
    public void run(String... args)  {
        log.debug("开始连接数据库");
        log.debug("\nurl={},\nusername={},\npassword={}",url,username,password);
        try {
            GeneratorActuator generatorActuator = SpringContextUtil.getBean(GeneratorActuator.class);

            generatorActuator.generator(force);
        }catch (SksException e){
            if("true".equalsIgnoreCase(printError)||logEnable){
                log.error(e.getMessage(),e);
            }else{
                log.error("*************加上 -l 参数可查看详细错误信息*************");
                log.error(e.getMessage());
            }
        }catch (Throwable e){
            log.error("错误",e);
        }

    }
}
